var favorite_url = 'favorite_only';
var unread_url = 'unread';

function PageStats() {
    var path = window.location.pathname;
    // <username>/tags/<tag_path>
    var user_re = /^\/(\d+)/;
    var tag_re = /tag\/([^\/]+)/;
    var subscription_re = /subscription\/(\d+)/;
    var unread_re = unread_url;
    var favorite_re = favorite_url;
    var user_match = path.match(user_re);
    if (user_match) {
        var user = user_match[1];
    } else {
        var user = null;
    }

    var tag_path = path.match(tag_re);
    if (tag_path == null) {
        tags = [];
    } else {
        tags = tag_path[1].split('+');
        for (var i = 0; i < tags.length; ++i) {
            tags[i] = decodeURIComponent(tags[i])
        }
    }

    var subscription = path.match(subscription_re);
    if (subscription != null) {
        subscription = subscription[1];
    }

    // Regexp occurs in the URL and is not a tag
    var check_not_tag = function(regexp) {
        var match = path.match(regexp)
        if (match != null) {
            if (tag_path != null && tag_path.index < match.index) {
                // 'unread' is just a tag
                var result = false;
            } else {
                var result = true;
            }
        } else {
            var result = false;
        }
        return result;
    }

    var unread_only = check_not_tag(unread_re);
    var favorite_only = check_not_tag(favorite_re);

    var OWNER_COOKIE_NAME = 'owner';
    var owner_string_start = document.cookie.indexOf(OWNER_COOKIE_NAME + '=') + OWNER_COOKIE_NAME.length + 1;
    if (owner_string_start != -1) {
        var owner_string_end = document.cookie.indexOf(';', owner_string_start);
        if (owner_string_end == -1) {
            owner_string_end = document.cookie.length;
        }
        var is_owner = document.cookie.substring(owner_string_start, owner_string_end) == 'true';
    }

    return {
        is_owner : is_owner,
        user : user,
        tags : tags,
        subscription : subscription,
        unread_only : unread_only,
        favorite_only : favorite_only
    };
}

var page_stats = PageStats();

function GetPathToStats(user, tags, subscription, unread_only, favorite_blogs_only) {
    var path = '/' + user;
    if (unread_only) {
        // Unread and favorite should always be placed before tags not to be confused with a tag with the same name.
        path += '/' + unread_url;
    }
    if (favorite_blogs_only) {
        path += '/' + favorite_url;
    }
    if (tags && tags.length > 0) {
        path += '/tag/' + TagsToPath(tags);
    }
    if (subscription) {
        path += '/subscription/' + subscription;
    }
    return path;
}

function NavigateToStats(user, tags, subscription, unread_only) {
    window.location.pathname = GetPathToStats(user, tags, subscription, unread_only);
}

function Map(array, func) {
    result = []
    for (var i = 0; i < array.length; ++i) {
        result.push(func(array[i]));
    }
    return result;
}

function Filter(array, func) {
    result = []
    for (var i = 0; i < array.length; ++i) {
        if (func(array[i])) {
            result.push(array[i]);
        }
    }
    return result;
}

function TagsToPath(tags) {
    return Map(tags, encodeURIComponent).join('+');
}

function TagLink(tag_name) {
    return '/' + page_stats.user + '/tag/' + encodeURIComponent(tag_name);
}

function SubscriptionLink(subscription_id) {
    var path = '/' + page_stats.user;
    if (page_stats.unread_only) {
        path += '/' + unread_url;
    }
    path += '/subscription/' + subscription_id;
    return path;
}

function SubscriptionEditLink(subscription_id) {
    return '/subscriptionEdit/' + subscription_id;
}

function Parameters() {
}

Parameters.prototype.toString = function() {
    var params = [];
    for (var name in this) {
        if (this.hasOwnProperty(name)) {
            params.push(name + '=' + this[name]);
        }
    }
    return params.join('&');
}

function GenerateLinkMarkup(tag_name, link, text, classes, onclick_action, id) {
    if (!classes) {
        classes = [];
    }
    var a_tag = $('<a/>');
    if (link) {
        a_tag.attr('href', link);
    } else {
        a_tag.attr('href', '#');
    }
    if (text) {
        a_tag.text(text);
    }
    if (onclick_action) {
        a_tag.bind('click', onclick_action);
    }
    var div_tag = $('<' + tag_name + '/>').append(a_tag);
    for (var i = 0; i < classes.length; ++i) {
        div_tag.addClass(classes[i]);
    }

    if (id) {
        div_tag.attr('id', id);
    }

    return div_tag;
}

function capitalizeFirst(string)
{
    return string[0].toUpperCase() + string.substr(1)
}

function createDeleteAction(item_type, item_id, action_list) {
    result = $('<span class="Action">Delete</span>').bind('click',  function(e) {
        var parent = $(e.target).parent();
        parent.children().addClass('Hidden');

        if (action_list == null) {
            action_list = [{ name : 'Yes', params : {} }]
        }

        var action_span = $('<span>Delete item</span>')
        for (var i = 0; i < action_list.length; ++i) {
            action_list[i].params.id = item_id;
            action_span.append(
                $('<span class="Action">' + action_list[i].name + '</span>').bind('click', function() {
                    var j = i;
                    return function(e) {
                        $.post('/delete' + capitalizeFirst(item_type), action_list[j].params, function(response) {
                            $('#' + item_type + '-' + item_id).remove()
                        })
                    }
                }())
            )
        }
        action_span.append(
            $('<span class="Action">No</span>').bind('click', function(e) {
                parent = $(e.target).parent();
                parent.siblings().removeClass('Hidden');
                parent.remove();
            })
        )
        parent.append(action_span);
    });
    return result;
}
